<!-- 数据分析 -->
<template>
  <div class="content">
    <div class="contentL" :class="{
      fadeOutLeftBig: !isCollopseLeft,
      fadeOutRightBig: isCollopseLeft,
    }">
      <div class="left-main app-wrapper">
        <el-input v-model="stationName" :placeholder="$t('licence.powe_stationNameMess')" clearable
          :prefix-icon="Search" style="margin-bottom: 20px; width: 226px" @change="searchList()" />

          <div class="infinite-list-wrapper" style="overflow: auto">
              <ul class="powerInver" v-infinite-scroll="loadMore" :infinite-scroll-disabled="loadOn"
                >
                <!-- 电站 -->
                <li class="powerList" v-for="(item, index) in powerList" :key="index">
                  <div @click="activesInverShow(index, item.id)" class="flexStart">
                    <!-- <i v-if="item.isPowerSelect" class="el-icon-caret-bottom" style="color: #dfdfdf"></i>
                    <i v-else class="el-icon-caret-top" style="color: #dfdfdf"></i> -->
                    <el-icon v-if="item.isPowerSelect" style="color: #dfdfdf"><CaretBottom /></el-icon>
                    <el-icon v-else style="color: #dfdfdf"><CaretRight /></el-icon>

                    <p class="powerName" :class="{ actives: item.selectIds.length > 0 }">{{ item.stationName }}</p>
                  </div>
                  <!-- 逆变器 -->
                  <div v-if="item.isPowerSelect">
                    <!-- 绑在电站上面 item.selectIds 每个电站的 selectIds-->
                    <el-checkbox-group v-model="item.selectIds" class="inverList">
                      <el-checkbox v-for="(child, idx) in inverList" :key="idx" :label="child.id" @change="checkInver()"
                        class="inverName" style="display: block !important">{{ child.psSn }}</el-checkbox>
                    </el-checkbox-group>
                    <!-- </div> -->
                  </div>
                </li>
                <p>{{ loadMsg }}</p>
              </ul>
          </div>
      </div>

      <i :class="{
        fadeOutLeftIcon: isCollopseLeft,
        fadeOutRightIcon: !isCollopseLeft,
      }" @click="collopseLeft"></i>
    </div>
    <div class="contentR">
      <h4 id="title">{{ $t('licence.inv_Title') }}</h4>
      <div class="main-content">
        <div class="title">
          <!-- 选择查询 -->
          <div class="time-box">
            <el-select style="width: 200px" v-model="powerState" :placeholder="$t('licence.inv_type0')" @change="selectChanged"
              clearable>
              <el-option v-for="item in options" :key="item.key" :label="$t('licence.inv_type' + item.key)"
                :value="item.key">
              </el-option>
            </el-select>
            <!-- 年月日选择 -->
            <el-date-picker style="margin: 0 20px; width: 260px" :clearable="true"
              v-model="startDay.stockDate" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
              :disabled-date="disabledDate" :placeholder="$t('licence.sta_selectDate')"
              @change="changeTime">
            </el-date-picker>
            <el-button @click="getInverterStatistics" type="primary" style="margin: 20px 0">{{ $t('licence.fau_Thequery')}}</el-button>
          </div>
          <!--  -->
          <div class="export" @click="Export">
            {{ $t('licence.sta_export') }}
          </div>
        </div>
        <!-- 数据曲线图 -->
        <div>
          <!-- 发电趋势 -->
          <div class="title" id="title" v-loading="loading">
            <div id="TrendcurveData" class="curveData" ref="curveData"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script name="Inverter" setup lang="ts">
import * as echarts from "echarts";
import {getpsStatisticExport,getpsDataExport,getstationList,getpsList,getpsCompare,getExport,} from "@/api/statisticalData/InverterStatistics";
import { Search } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
      const disabledDate = (time:any)=>{
          return time.getTime() > Date.now();
        }
      const isCollopseLeft = ref(true) // 默认不折叠
      const stationName = ref('') //电站名称
      type PowerListItem = {
        id: number;
        isPowerSelect: string;
        selectIds: number[];
        stationName: string;
      }

      const powerList = ref<PowerListItem[]>([])
      const inverList = ref([{
        id:'',
        psSn:'',
      }])

      // 分页
      const queryData = reactive ({
        page: 1, // 当前页码
        pagesize: 10, //每页条数
        total: 0, // 总数
      })
      // const scrollCount = ref(0)
      // const scrollUserLoading = ref(false)
      // const checkedList = ref([]) //复选框选择
      const loadOn = ref(false)
      const loadMsg = ref( "加载中...") //加载信息

      //=============
      const powerStation= ref({
        id:-1
      }) //获取保存电站信息
      // 时间选择器
      const getNowTime = ():string => {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1;
        const date = now.getDate();

        const defaultDate = `${year}-${month.toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`;
        return defaultDate;
      }
      const startDay = ref({
        stockDate: getNowTime() //日期选择
      })
      // 下拉选择状态
      // 查询状态
      const options = [
        {
          key: 0,
        },
        {
          key: 1,
        },
        {
          key: 2,
        },
        {
          key: 3,
        },
        {
          key: 4,
        },
        {
          key: 5,
        },
        {
          key: 6,
        },
        {
          key: 7,
        },
        {
          key: 8,
        },
        {
          key: 9,
        },
      ]
      const powerState = ref(0) //查询下拉绑定默认字段
      // const currentSetOptions = ref(null)
      // const exportAttritute = ref(null)
      const lang = ref(0)
      const loading = ref(false) //加载状态
      const timer = ref()
    //  侧边栏展开
    const collopseLeft = () => {
      isCollopseLeft.value = !isCollopseLeft.value;
    }
    const loadMore = () => {
      getPowerList();
    }
    const searchList = () => {
      if (timer.value) {
        clearTimeout(timer.value);
      }
      timer.value = setTimeout(() => {
        powerList.value = JSON.parse(JSON.stringify([]));
        queryData.page = 1;
        getPowerList();
      }, 500);
    }
    // 获取电站列表
    const getPowerList = () => {
      loadOn.value = true;
      let ids:any[] = [];
      getstationList({
        stationName: stationName.value,
        stationIds: ids.join(","),
        pageNo: queryData.page,
        pageSize: queryData.pagesize,
      })
        .then((res) => {
          res.data.list.forEach((item:any) => {
            item.isPowerSelect=false; // 默认都未选择不展开 false
            // 首先要把逆变器和电站绑定起来 电站和逆变器有关联 1-1对应 用来存放绑定的逆变器ID
            item.selectIds=[];
          });
          powerList.value = powerList.value.concat(res.data.list);
          // powerList.value[0].isPowerSelect = true
          if (res.data.list.length < queryData.pagesize) {
            //当请求数据是最后一页时
             //最后一页时，关闭触发请求的开关
            loadMsg.value = ""; //修改加载信息，给用户一个提示
          } else {
            queryData.page += 1;
            //当请求数据不是最后一页时
            loadOn.value = false; //加载完成后，打开触发请求的开关
          }
        })
        .catch((error) => console.log(error));
    }
    // 点击展开电站 获取逆变器
    const activesInverShow = (index:any, item:any) => {
      powerList.value.forEach(async (item:any, idx:any) => {
        // item.isPowerSelect = false
        // 展开与隐藏
        if (index == idx) {
          item.isPowerSelect = !item.isPowerSelect;
          // 展开时获取逆变器
          if (item.isPowerSelect == true) {
            // 逆变器获取接口
            inverList.value = [];
            let res = await getpsList({
              stationId: item.id,
            });
            inverList.value = res.data;
          }
        } else {
          item.isPowerSelect = false;
          inverList.value = [];
          //关掉时清空逆变器的数组
        }
      });
      getInverterStatistics();
    }
    // 侧边栏选中逆变器
    const checkInver = () => {
      // currentData.selectIds.join(",")
      let ids = [];
      // 拿到当前展开的逆变器数据
      let currentData:any = {};
      powerList.value.forEach((item) => {
        if (item.isPowerSelect) {
          currentData = item;
          ids = [item.id];
        }
      });
      getInverterStatistics();
      // 1.首先判断有无选中元素
      if (currentData.selectIds.length > 0) {
        let idx:any;
        let selData:any = {};
        powerList.value.forEach((item, index) => {
          if (item.isPowerSelect) {
            // 拿到逆变器的索引
            idx = index;
            // 拿到逆变器的数据
            selData = item;
          }
        });
        // 删除当前
        powerList.value.splice(idx, 1);
        // 然后添加到第一位
        powerList.value.unshift(selData);
      } else {
        let idx:any;
        let selData:any = {};
        powerList.value.forEach((item, index) => {
          if (item.isPowerSelect) {
            // 拿到逆变器的索引
            idx = index;
            // 拿到逆变器的数据
            selData = item;
          }
        });
        // 删除当前
        powerList.value.splice(idx, 1);
        // push到数组后面
        powerList.value.push(selData);
      }
    }
    const changeTime = (val:any) => {
      proxy!.$forceUpdate(); //需要使用强制更新
      startDay.value.stockDate = val;
    }
    // 导出
    const Export = async() => {
      let ids:any[] = [];
      // 所有的id不都绑定在了电站上面了吗  selectIds
      powerList.value.forEach((item) => {
        ids = [...ids, ...item.selectIds];
      });
      const res = await getExport({
        psIds: ids.join(","),
        optionType: powerState.value + 1,
        searchDay: startDay.value.stockDate,
        lang: lang.value,
      });
      let url = window.URL.createObjectURL(
        new Blob([res], { type: "application/vnd.ms-excel" })
      );
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", t("licence.inv_tongji") + ".xls");
      document.body.appendChild(link);
      link.click();
    }
    // 逆变器统计
    const getInverterStatistics = async () => {
      loading.value = true;
      let ids:any = [];
      // 所有的id不都绑定在了电站上面了吗  selectIds
      powerList.value.forEach((item) => {
        ids = [...ids, ...item.selectIds];
      });
      let query = {
        psIds: ids.join(","),
        lang: lang.value,
        searchDay: startDay.value.stockDate,
        optionType: powerState.value + 1,
      };
      let res = await getpsCompare(query);
      let series:any[] = []; //数据
      if (res.data.charts.series == null) {
        ElMessage({
          message: "暂无数据",
          type: "warning",
        });
        loading.value = false;
      } else {
        res.data.charts.series.forEach((item:any, index:any) => {
          series.push({
            name: item.source,
            type: "line",
            showSymbol: false, //不显示折线图上的圆点
            //  stack: 'Total',
            lineStyle: {
              width: 1, //设置线条粗细
            },
            data: item.data,
            smooth: true
          });
        });
      }
      getTrendcurveData(res.data.charts, series);
      loading.value = false;
    }
    // 图表
    const getTrendcurveData = (data:any, series:any) => {
      const myChart = echarts.init(document.getElementById("TrendcurveData") as HTMLElement)as echarts.ECharts;
      myChart.setOption(
        {
          // 悬浮提示
          tooltip: {
            show: true,
            trigger: "axis",
            backgroundColor: "#656565",
            textStyle: { color: "#ffffff" },
            extraCssText: "box-shadow: 0px 2px 5px 0px rgba(50,107,174,0.19);",
          },
          legend: {
            itemHeight: 12,
            itemWidth: 12,
            icon: "circle",
          },
          // 位置
          grid: {
            left: "4%",
            right: "3%",
            // bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: data.categories,
          },
          yAxis: [
            {
              type: "value",
              // name: data.series[0].unit,
              axisTick: {
                show: false,
              },
              axisLine: {
                show: false,
              },
              axisLabel: {
                formatter: "{value}",
              },
              min: 0,
            },
          ],
          series: series,
        },
        true
      );
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    }
    const selectChanged = (value:number)=> {
      powerState.value = value;
      getInverterStatistics();
    }
    watch(stationName,
        (val)=> {
          if (val !== "") {
            searchList();
          }
      }, { deep: true}
    )
    onMounted(()=>{
      // 获取语言
      if (localStorage.getItem("locale") == "en_US") {
        lang.value = 1;
      } else {
        lang.value = 0;
      }
      // 电站列表
      // getPowerList();
      // 获取电站信息
      powerStation.value = JSON.parse(localStorage.getItem("powerStation") as string);
      // 逆变器统计
    })
</script>
<style scoped lang="scss">
* {
  margin: 0;
  box-sizing: border-box;
  list-style: none;
}

.content {
  display: flex;
  justify-content: space-between;
  height:calc(100vh - 100px) !important;
  .contentL {
    position: relative;
    width: 274px;
    height: 100%;
    background: #ffffff;
    border-radius: 6px 0px 0px 6px;
    padding: 20px;
    margin-right: 20px;

    .left-main {
      width: 100%;
      //   height: 100%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: scroll;

      .powerInver {
        padding: 0 !important;
        line-height: 25px;
        height: calc(100% - 100px);

        .powerList {
          margin-bottom: 5px;
          cursor: pointer;

          .powerName {
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 600;
            color: #222222;
            margin-left: 6px;
          }

          .actives {
            color: #305add !important;
          }
        }

        .inverList {
          margin-left: 26px;

          .inverName {
            display: block !important;
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #1f2e4d;
            line-height: 30px;
          }

          // 选择框样式修改
          ::v-deep .el-checkbox {
            display: block !important;
          }

          // //选择框的颜色
          ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
            background-color: #305add;
            border-color: #305add;
          }

          ::v-deep .el-checkbox__label {
            color: #1f2e4d;
          }
        }
      }
    }

    .fadeOutLeftIcon {
      position: absolute;
      top: 50%;
      right: 0;
      transform: translateY(-50%);
      cursor: pointer;
      width: 16px;
      height: 32px;
      background: url(../../../assets/images/left.png) no-repeat;
    }

    .fadeOutRightIcon {
      position: absolute;
      top: 50%;
      left: -20px;
      transform: translateY(-50%);
      z-index: 999;
      cursor: pointer;
      width: 16px;
      height: 32px;
      background: url(../../../assets/images/right.png) no-repeat;
    }
  }

  .contentR {
    flex: 1;
    background: #ffffff;
    padding: 20px 20px 30px 20px;

    // 右边样式修改
    // 曲线图
    .curveData {
      width: 100% !important;
      height: 600px;
      // background-color: #FFF;
    }

    #title {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 600;
      color: #0e1319;
      margin-bottom: 20px;
    }

    // ========
    .title {
      display: flex;
      align-items: baseline;

      .time-box {
        flex: 1;
        margin: -20px 0 20px 0px;

        // 年月日选择
        ::v-deep .el-radio-button__inner {
          border: none;
          border-radius: 4px;
          background: #e7e7e7;
          margin-left: 10px;
        }

        ::v-deep .el-radio-button:first-child .el-radio-button__inner {
          border-radius: 4px;
        }

        ::v-deep .el-radio-button--mini .el-radio-button__inner {
          padding: 6px 12px;
        }
      }
    }

    .export {
      width: 70px;
      height: 36px;
      border-radius: 4px;
      border: 1px solid #dddfe6;
      font-size: 14px;
      text-align: center;
      line-height: 36px;
      cursor: pointer;
    }

    .active {
      color: #305add;
    }

    // 查询按钮
    .el-button--primary {
      color: #ffffff;
      background-color: #305add;
      border-color: #305add;
      // padding: 12px 20px;
    }
  }

  .iconR {
    position: relative;
  }
}

// 左侧样式
.home-left {
  width: 274px;
  position: relative;
}

// 左侧淡出
.fadeOutLeftBig {
  animation: 0.5s fadeOutLeftBig forwards;
}

@keyframes fadeOutLeftBig {
  0% {
    width: 274px;
  }

  100% {
    width: 0px;
    padding: 0;
  }
}

// 左侧淡入
.fadeOutRightBig {
  animation: 0.5s fadeOutRightBig forwards;
}

@keyframes fadeOutRightBig {
  0% {
    width: 0px;
    padding: 0;
  }

  100% {
    width: 274px;
  }
}
</style>
